/**
 * useRequest 请求
 * @author SPY
 * @date 2020/04/11
 */

import React from 'react';
import { Table, Avatar, Button, Space } from 'antd';
import { useRequest, useFullscreen } from '@umijs/hooks';
import { queryList } from '@/services/umiHooks';

const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    width: 50,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 50,
    render: (text: any) => <span>{text === 'male' ? '男' : '女'}</span>,
  },
  {
    title: '头像',
    dataIndex: 'picture',
    width: 50,
    render: (text: any) => <Avatar shape="square" size={50} src={text} />,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 50,
  },
];

const BasicRequest = () => {
  // 设置全屏
  const { setFull } = useFullscreen<HTMLElement>({
    dom: (): any => document.getElementById('fullscreen'),
  });

  const { data, error, loading, run, cancel, tableProps } = useRequest(
    ({ current, pageSize }) =>
      queryList({
        results: pageSize,
        inc: 'name,email,picture,login,gender',
        page: current,
      }),
    {
      manual: false, // true:表示手动触发接口，false:表示第一次进入时会自动触发接口
      pollingInterval: 3000, // 3秒执行一次轮训
      pollingWhenHidden: false, // 窗口不可见时，暂时暂停定时任务
      paginated: true, // 开启分页管理模式
      formatResult: response => {
        const { results } = response;
        const newResponse: Array<{}> = [];
        results.forEach((item: any) => {
          newResponse.push({
            id: item.login.uuid,
            name: item.name.first,
            picture: item.picture.large,
            gender: item.gender,
            email: item.email,
          });
        });
        return Object.assign({}, { total: 100, list: newResponse });
      },
      defaultPageSize: 5, // 默认页数
      onSuccess: () => {},
    },
  );
  if (error) return <span>请求数据失败</span>;
  return (
    <>
      <Space style={{ marginBottom: 6 }}>
        <Button type="primary" onClick={() => run({ pageSize: 5, current: 1 })}>
          刷新/开启轮询
        </Button>
        <Button onClick={cancel}>停止轮询</Button>
        <Button onClick={setFull}>全屏</Button>
      </Space>
      <Table
        id="fullscreen"
        {...tableProps}
        rowKey="id"
        columns={columns}
        // dataSource={data?.list}
        // loading={loading}
        pagination={{
          ...tableProps.pagination,
          showQuickJumper: true,
        }}
      />
    </>
  );
};

BasicRequest.title = 'useRequest 使用';

export default BasicRequest;
